<?php
/**
 * Update a new Medical Study.
 *
 */
use Nawa\MedicalStudy\Authorization;
use Nawa\MedicalStudy\MedicalCenter;
use Fox\Msg;
use Fox\Message;
use Nawa\MedicalStudy\Followup;
use Nawa\MedicalStudy\Partner;
use Fox\Generator;
use Fox\Html\Header\Image;
use Nawa\Customer;
use Nawa\MedicalStudy;
use Fox\Core\Errors;
use Fox\Html\Button;
use Fox\Html\Screen;

$xview = Xview::instance();

// Load Breadcrumb Data
$id = $xview->val('msid');
try {
	$update = false;
	$ms = Fox\Dao::load(MedicalStudy::className(),$id);
	
	if(Authorization::check(Authorization::MS_UPDATE,$ms)) {
		$update = true;
	}
	elseif(!Authorization::check(Authorization::MS_VIEW,$ms)) {
		$xview->accessDenied();
	}
	
	$data = $ms->getData();
	foreach($ms->metadatas() as $metadata) {
		$data = array_merge($data,$metadata->parse());
	}
	
	$customer = $ms->customer();
	$msCenterCount = 0;
	// Initialize Partners
	foreach($ms->partners() as $partner)
	{
		switch($partner->role)
		{
			case MedicalStudy::ROLE_CUSTOMER :
				$customerPartner = $partner;
				break;
			default:
				$detail = $partner->getData();
				$detail['medicalcenters'] = null;
				$detail['name1'] = $partner->customer()->name1;
				
				foreach($partner->medicalCentersLinks() as $center)
				{
					/* @var $center Nawa\MedicalStudy\MedicalCenter\Partner */
					try {
						$mc = $center->medicalCenterPartner()->medicalCenter();
						$detail['medicalcenters'][] = array('label' =>$mc->name1,'mcid' => $mc->mcid);
					} catch(Fox\Object\Exception\NotExist $e) {
						// Should not be possible
						
					}
				}
				
				if(!empty($detail['medicalcenters'])) {
					$detail['medicalcenters'] = preg_replace("/\"/","'",json_encode($detail['medicalcenters']));
				}
				$data['gPartners'][] = $detail;
				$partners[$partner->customerid] = $partner;
				break;
		}
	}
	
	foreach($ms->medicalCentersPartners() as $medicalCenter)
	{
		$data['gMedicalCentersPartners'][$medicalCenter->mcid] = array_merge($medicalCenter->getData(),
		$medicalCenter->medicalCenter()->getData());
		$medicalCenters[$medicalCenter->mcid] = $medicalCenter;
		$msCenterCount++;
	}
	$followups = array();
	// Followup Items
	foreach($ms->followup() as $item) {
		$data['followup'][] = $item->getData();
		$followups[$item->itemid] = $item;
	}

}
catch (Fox\Object\Exception\NotExist $e)
{
	var_dump($e);
	//$xview->accessDenied();
}

$screen = new Screen('sMS','update');

$screen->mainTitle(new Image('medicalstudy','<div class="page-title">'.Msg(Nawa\Messages::BUNDLE,Nawa\Messages::MS_UPDATE_LABEL).'</div>'));
/*$screen->toolbar()->add(new Button('copy',
Generator::display('msCopy',
Generator::url('medicalstudies','bycopy')),
Msg(Fox\Msg::BUNDLE,Fox\Msg::BUT_CREATE_BY_COPY)));
*/
// Master Data
$bHeader = Xview::instance()->component('medicalstudies', 'header');
$screen->add($bHeader);
if($customer->exists())
{
	$bHeader->item('customerid')->input(false);
}
$bHeader->item('status')->input(false);
// Follow Up Customizing
$bFollowup = $xview->module(Generator::url('medicalstudies', 'followup'));
$screen->add($bFollowup);
// Monitoring Checklist
$bCheckList = $xview->component('medicalstudies', 'checklists');
if(!empty($data['checklists'])) {
	$bCheckList->initialize($data['checklists']);
}
$screen->add($bCheckList);
// Partners - Employee
$bPartners = $xview->module(Generator::url('medicalstudies', 'partners'));
$screen->add($bPartners);
// Partners - Medical Centers
$bMC = $xview->module(Generator::url('medicalstudies', 'medicalcenters'));
$screen->add($bMC);
$screen->initialize($data);

if($screen->submitted())
{
	$fields = $screen->get();
	if(is_array($fields['followup'])) {
		uasort($fields['followup'],function($a, $b){
			if($a['position'] > $b['position'])	{
				return 1;
			} else {
				return -1;
			}
		});
		$bFollowup->item('followup')->initialize($fields['followup'],true);
	}
	if(!$screen->errors())
	{
		try {
			unset($fields['msid']);
			$ms->setFields($fields);
			$ms->responsibleid = User::current()->getId();

			// Customer
			if(!isset($customerPartner)) {
				$customerPartner = new Partner();
				$customerPartner->role = MedicalStudy::ROLE_CUSTOMER;
			}
			$customerPartner->setFields(array('customerid' => $fields['customerid']));
			$ms->replacePartners($customerPartner);

			// Attach Customer Partner
			if(is_array($fields['gPartners']))
			{
				foreach($fields['gPartners'] as $partnerData)
				{
					if(!isset($partnerData['customerid'])) {
						continue;
					}
					$id = $partnerData['customerid'];
					if(isset($partners[$id]))
					{
						$partner = $partners[$id];
						unset($partners[$id]);
					}
					else
					{
						$partner = new Partner();
					}
					$partner->setFields($partnerData);
					$ms->replacePartners($partner);
				}
			}
			// Attach Medical Center Partner
			if(is_array($fields['gMedicalCentersPartners']))
			{
				$msCenterCount = count($fields['gMedicalCentersPartners']);
				foreach($fields['gMedicalCentersPartners'] as $partnerData)
				{
					if(!isset($partnerData['mcid']))  {
						continue;
					}
					
					$id = $partnerData['mcid'];
					unset($partnerData['msid']);
					if(isset($medicalCenters[$id]))
					{
						$partner = $medicalCenters[$id];
						unset($medicalCenters[$id]);
					}
					else
					{
						$partner = new MedicalCenter();
					}
					$partnerData['role'] = MedicalStudy::ROLE_MEDICAL_CENTERS;
					$partner->setFields($partnerData);
					$ms->replaceMedicalCentersPartners($partner);
					$data['gMedicalCentersPartners'][$id] = $partnerData;
			
				}

			}
			// Remove delete Partners
			if(isset($partners) && is_array($partners))
			{
				foreach($partners as $partner)
				{
					$ms->deleteFromPartners($partner);
				}
			}
			// Remove delete Centers
			if(isset($medicalCenters) && is_array($medicalCenters))
			{
				//@TODO add a Check before deletion
				foreach($medicalCenters as $centerLink)
				{
					// Check if there are partners associate to this 
					// medical center 
					if($centerLink->countPartners() > 0) {
						// Re-Add information 
						$reinit['gMedicalCentersPartners'] = $data['gMedicalCentersPartners'];
						$screen->initialize($reinit);
						throw new Exception(Msg(Nawa\Messages::BUNDLE,
												Nawa\Messages::MS_MC_DELETE_ERROR_NOT_EMPTY,
												$centerLink->medicalCenter()->label()));
					}
					$ms->deleteFromMedicalCentersPartners($centerLink);
				}
			}
			// Handle Checklist Metadata
			foreach($bCheckList->get() as $fieldname => $value) {
				$checklistMetadata[$fieldname] = $value;
			}
			if(!empty($checklistMetadata)) {
				$metadatas['checklists'] = json_encode($checklistMetadata);
				
			}
			if(!empty($metadatas)) {
				foreach($metadatas as $name => $value) {
					$metadata = new MedicalStudy\Metadata();
					$metadata->setFields(array('msid' => $ms->getId(),'metadata_name' => $name,'value' => $value));
					$ms->replaceMetadatas($metadata);
				}
			}
			
			// Update Followup Information
			if(is_array($fields['followup']))
			{
				foreach($fields['followup'] as $followupData) {
					if(isset($followups[$followupData['itemid']])) {
						$followup = $followups[$followupData['itemid']];
						$followup->setFields(array(
							'code' => $followupData['code'],
							'position' => $followupData['position']
						));
						$ms->replaceFollowup($followup);
						unset($followups[$followupData['itemid']]);
					} else {
						// @TODO set an error because it should not 
						// be possible in the current workflow
						// has data are saved during update
					}
					
				} 
			}
			// Remove Delete Followup Item
			foreach($followups as $item) {
				$ms->deleteFromFollowup($item);
			}
			// Metadata
			
			
			// Update MS
			$ms->prepareUpdate(MedicalStudy::CHANGE_DEFAULT);
			if($ms->update()){
				Message::Success(Msg(Msg::BUNDLE,Msg::MSG_UPDATE,$ms->reference));
			} else {
				Message::Information(Msg(Msg::BUNDLE,Msg::MSG_NO_UPDATE,$ms->reference));
			}
		}
		catch (Fox\Object\Exception\Save $e)
		{
			Fox\Message::Error($e);
		}
		catch (\Exception $e)
		{
			Fox\Message::Error($e->getMessage());
		}
	}
}
// Bread Crumb
$crumbs = Xview::instance()->component('medicalstudies','breadcrumb',
array('deepness' => 2,
									  'customerid' => $customer->getId(),
									  'customer_name' => $customer->name1,
									  'msReference' => $ms->reference,
									  'msid' => $ms->getId(),
									  'msCenterCount' => $msCenterCount));
$screen->breadcrumb()->crumbs($crumbs);

echo $screen->display();